﻿Option Explicit On

Imports System.ComponentModel
Imports System.Text
Imports System.IO
Imports System.Data
Imports System.Windows.Forms
Imports Microsoft.Office.Interop
Imports Global_Visas_Business_Layer

Public Class frmAdminNewLetterReg

    Private _LetterId As Integer
    Private _LetterName As String
    Private OpenFileDialog1 As OpenFileDialog

    Private ReadOnly Property DocumentType() As Integer
        Get
            If Me.radWord.IsChecked Then
                Return 1
            Else
                Return 2
            End If
        End Get
    End Property

    Private ReadOnly Property ClientType() As Integer
        Get
            If Me.radAnyClient.IsChecked Then
                Return 0
            ElseIf Me.radPrivClient.IsChecked Then
                Return 1
            ElseIf Me.radCorpClient.IsChecked Then
                Return 2
            End If

        End Get
    End Property

    Private ReadOnly Property OutputType() As Integer
        Get
            If Me.radOutAny.IsChecked Then
                Return 0
            ElseIf Me.radOutPrint.IsChecked Then
                Return 1
            ElseIf Me.radOutEmail.IsChecked Then
                Return 2
            ElseIf Me.radOutFile.IsChecked Then
                Return 3
            End If
        End Get
    End Property

    Public Property LetterId() As Integer
        Get
            Return _LetterId
        End Get
        Set(ByVal value As Integer)
            _LetterId = value
        End Set
    End Property

    Public Property LetterName() As String
        Get
            Return _LetterName
        End Get
        Set(ByVal value As String)
            _LetterName = value
        End Set
    End Property

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub AdminNewLetterReg_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Loaded
        GeneralTasks.ChangeTheme(Me)
        GeneralTasks.EnumerateandFill(Me.LogicalChildren)
        With Me.drpType
            .DisplayMemberPath = "LetterType_Name"
            .SelectedValuePath = "LetterType_ID"
            .ItemsSource = CType(Letters.LetterTypeList, IListSource).GetList
            .SelectedIndex = -1
        End With
    End Sub

    Private Sub btnFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFile.Click
        OpenFileDialog1 = New OpenFileDialog
        If Me.OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.txtPath.Text = Me.OpenFileDialog1.FileName
        End If
    End Sub

    Private Sub btnScanBookmarks_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnScanBookmarks.Click

        'Word Automation declarations
        Dim WordApp As Word.Application, WordDoc As Word.Document, ObjBookmark As Word.Bookmark

        'General declarations

        Dim StrBookmarks As String, StrUnknown As String, StrInvalid As String, StrDLList As String, IntCtype As Integer, StrMsg As String, IntBMFound As Integer, StrID As String, StrLegacy As String
        Dim IntWordActive As Integer
        Dim StrFile As String
        Dim SQL As New StringBuilder
        Dim myData As DataTable
        Dim myRow As DataRow
        Dim myBookmark As Letters.BookmarkInfo
        Dim DataLevelCustomerType As String
        Dim Ret As MsgBoxResult

        If Me.drpType.SelectedIndex = -1 Then
            MsgBox("You need to select a lettertype before scanning the document", MsgBoxStyle.Exclamation, "Error")
            Exit Sub
        End If

        'Me.Cursor = Cursors.WaitCursor


        WordApp = New Word.Application
        WordApp.Visible = False
        IntWordActive = 1

        StrFile = Me.txtPath.Text.Trim

        'Set up list of datalevels that this doc should be using.

        With SQL
            .Append("SELECT I_SL_DataLink.DataLink_DataLevelID")
            .Append(" FROM I_SL_LetterTypes INNER JOIN I_SL_DataLink ON I_SL_LetterTypes.LetterType_DataGroupID = I_SL_DataLink.DataLink_DataGroupID")
            .Append(" WHERE I_SL_LetterTypes.LetterType_ID = " & Me.drpType.SelectedValue)
        End With

        myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

        If myData.Rows.Count = 0 Then
            'Me.Cursor = Cursors.Default
            MsgBox("No datalevels found for this lettertype!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If


        For Each myRow In myData.Rows
            StrDLList = StrDLList & "_X" & myRow.Item("datalink_datalevelID") & "X_"

        Next

        myData.Dispose()

        WordDoc = New Word.Document

        WordDoc = WordApp.Documents.Add(StrFile)

        'document has been opened, scan for bookmarks



        For Each ObjBookmark In WordDoc.Bookmarks

            If IntBMFound = 0 Then IntBMFound = 1

            myBookmark = Letters.GetBookmark(ObjBookmark.Name)

            If myBookmark.Bookmark_ID = 0 Then

                'Unknown bookmark, check for re-use (bookmark name followed by a digit)
                If IsNumeric(Strings.Right(ObjBookmark.Name, 1)) Then

                    'Might be a re-used bookmark, check and see
                    myBookmark = Letters.GetBookmark(Strings.Left(ObjBookmark.Name, (Len(ObjBookmark.Name) - 1)))

                    If myBookmark.Bookmark_ID = 0 Then
                        'hasnt been found with one digit, try with two

                        If IsNumeric(Strings.Right(ObjBookmark.Name, 2)) Then

                            myBookmark = Letters.GetBookmark(Strings.Left(ObjBookmark.Name, (Len(ObjBookmark.Name) - 2)))

                            If myBookmark.Bookmark_ID = 0 Then
                                'still not found, this is unknown


                                StrUnknown = StrUnknown & ObjBookmark.Name & Chr(13) & Chr(10)
                            Else
                                'Its a re-used bookmark with two digits, so ignore it
                            End If
                        Else
                            'Unrecognised bookmark
                            StrUnknown = StrUnknown & ObjBookmark.Name & Chr(13) & Chr(10)
                        End If
                    Else
                        'Its a re-used bookmark with one digit, so ignore it
                    End If
                Else
                    'Unrecognised bookmark
                    StrUnknown = StrUnknown & ObjBookmark.Name & Chr(13) & Chr(10)
                End If
            Else
                'Recognised bookmark, check the data level against the list
                IntBMFound = 2

                If myBookmark.Bookmark_Legacy = 1 Then
                    'Old legacy bookmark, add to list for warning
                    StrLegacy = StrLegacy & ObjBookmark.Name & vbCrLf
                End If

                'Add it to the list.
                StrBookmarks = StrBookmarks & ObjBookmark.Name & vbCrLf

                'is this bookmark in the list of legal datalevels for this letter
                If InStr(StrDLList, "X" & myBookmark.BookMark_DataLevelID & "X") = 0 Then
                    StrInvalid = StrInvalid & ObjBookmark.Name & vbCrLf
                End If

                'Check Customer Type of datalevel.

                DataLevelCustomerType = CommonDataFunctions.GetSQLScalar("Select Datalevel_CustomerType from I_SL_Datalevels where Datalevel_ID = " & myBookmark.BookMark_DataLevelID)

                'strSQL = "Select Datalevel_CustomerType from I_SL_Datalevels where Datalevel_ID = " & IntDL

                'Rst = GSS(strSQL)
                'If Rst.RecordCount = 0 Then
                '    Call MsgBox("Error, datalevel not found")
                '    Exit Sub
                'End If

                If DataLevelCustomerType <> 0 Then

                    'This bookmark is for a specific customer type, record for later checking

                    If IntCtype = 0 Then
                        IntCtype = DataLevelCustomerType
                    Else
                        If IntCtype <> DataLevelCustomerType Then
                            'Both private only and corporate only bookmarks present!
                            IntCtype = 100
                        End If
                    End If
                End If



            End If
        Next

        'Got all the bookmarks, close the word object and generate the report

        WordApp.Quit(SaveChanges:=Word.WdSaveOptions.wdDoNotSaveChanges)
        WordDoc = Nothing
        WordApp = Nothing

        'Did we find any bookmarks?
        If IntBMFound = 0 Then

            'No bookmarks, leave type alone
            'Me.Cursor = Cursors.Default
            MsgBox("This letter contains no bookmarks at all, it can be used with any letterpack for any client type and will appear exactly as it was created", MsgBoxStyle.Information)

            Exit Sub
        End If

        'did we recognise any bookmarks?
        If IntBMFound = 1 Then

            'No recognised bookmarks, leave type alone

            'Me.Cursor = Cursors.Default
            MsgBox("This letter contains no recognised bookmarks at all, it can be used with any letterpack for any client type and will appear exactly as it was created." & Chr(13) & Chr(10) & "The following unrecognised bookmarks were found" & Chr(13) & Chr(10) & "------------------------------------------------------" & Chr(13) & Chr(10) & StrUnknown, MsgBoxStyle.Information)

            Exit Sub
        End If

        'List the recognised ones we found

        'Me.Cursor = Cursors.Default

        MsgBox("The following bookmarks were found" & Chr(13) & Chr(10) & "---------------------------------------------" & Chr(13) & Chr(10) & StrBookmarks, MsgBoxStyle.Information)

        If StrLegacy <> "" Then
            StrLegacy = "The following legacy bookmarks were detected." & vbCrLf & vbCrLf & StrLegacy & vbCrLf & vbCrLf & "These will work, but may not be supported in the future." & vbCrLf & "If possible they should be replaced with the bookmarks on the printed list"
            MsgBox(StrLegacy, MsgBoxStyle.Information, "Legacy Bookmarks detected")
        End If

        'Did we find any client specific bookmarks with an invalid customer type for the letter?
        If IntCtype > 0 And Me.ClientType <> IntCtype Then

            Select Case IntCtype

                Case 1
                    'Private only bookmarks in letter.
                    If Me.ClientType = 0 Then
                        'Any Letter with private bookmarks
                        MsgBox("This file contains bookmarks that are specific to private individuals, it cannot be used with an 'any' letter" & vbCrLf & vbCrLf & "The client type for the letter will be changed automaticaly.", MsgBoxStyle.Exclamation, "Error")
                        Me.radPrivClient.IsChecked = True
                        Me.grpClientTypes.isEnabled = False

                    Else
                        'Corporate letter with private bookmarks
                        MsgBox("This file contains bookmarks that are specific to private individuals, it cannot be used with a 'Corporate' letter" & vbCrLf & vbCrLf & "The client type for the letter will be changed automaticaly.", MsgBoxStyle.Exclamation, "Error")
                        Me.radPrivClient.IsChecked = True
                        Me.grpClientTypes.IsEnabled = False

                    End If

                Case 2
                    'Company Letter with private bookmarks.
                    If Me.ClientType = 0 Then
                        'Any Letter with corporate bookmarks
                        MsgBox("This file contains bookmarks that are specific to corporate clients, it cannot be used with an 'any' letter" & vbCrLf & vbCrLf & "The client type for the letter will be changed automaticaly.", MsgBoxStyle.Exclamation, "Error")
                        Me.radCorpClient.IsChecked = True
                        Me.grpClientTypes.IsEnabled = False
                    Else
                        'Private Letter with Corporate Bookmarks
                        MsgBox("This file contains bookmarks that are specific to corporate clients, it cannot be used with a 'Private' letter" & vbCrLf & vbCrLf & "The client type for the letter will be changed automaticaly.", MsgBoxStyle.Exclamation, "Error")
                        Me.radCorpClient.IsChecked = True
                        Me.grpClientTypes.IsEnabled = False
                    End If

                Case 100
                    'Contains both private and corporate bookmarks, cannot be used.

                    MsgBox("This letter contain bookmarks that are specific to both private individuals, and corporate clients. This is an invalid configuration and cannot be used. Please amend the file then register again.", MsgBoxStyle.Exclamation, "Error")
                    Me.btnSave.IsEnabled = False

                    Exit Sub
            End Select



        End If
        'Letters bookmarks are approproate for the customer type, if this is a customer specific letter, check the Letterpacks where this has been used to make sure they are valid.
        If Me.ClientType > 0 And Me.LetterId > 0 Then
            'Not an 'any' letter and already in use, has the letter already been used incorrectly in a letterpack?

            SQL = New StringBuilder

            With SQL
                .Append("SELECT D_LetterPacks.LetterPack_Name, D_LetterLink.LetterLink_ID")
                .Append(" FROM D_LetterLink INNER JOIN D_LetterPacks ON D_LetterLink.LetterLink_LetterPackID = D_LetterPacks.LetterPack_ID")
                .Append(" WHERE D_LetterLink.LetterLink_LetterID)=" & Me.LetterId & ") AND ((D_LetterLink.LetterLink_CustomerType <> " & Me.ClientType)
            End With

            myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

            If myData.Rows.Count > 0 Then



                StrID = ""

                For Each myRow In myData.Rows
                    'List of names to show the user
                    StrMsg = StrMsg & myRow.Item("letterpack_name") & ", "

                    'List of Id's to delete if they want
                    If StrID <> "" Then StrID = StrID & ", "
                    StrID = StrID & myRow.Item("LetterLink_ID")


                Next

                myData.Dispose()

                If Me.ClientType = 2 Then

                    Ret = MsgBox("This letter uses company specific bookmarks but has been used as an 'individual' or 'all' letter in the following letterpacks" & Chr(13) & Chr(10) & "---------------------------------------------" & Chr(13) & Chr(10) & StrMsg & Chr(13) & Chr(10) & "---------------------------------------------" & Chr(13) & Chr(10) & Chr(13) & Chr(10) & "If left as is, it will not print out corectly." & vbCrLf & "Would you like these links to be removed automaticaly?", vbYesNo + vbExclamation, "Warning")
                Else
                    Ret = MsgBox("This letter uses individual specific bookmarks but has been used as a 'corporate' or 'all' letter in the following letterpacks" & Chr(13) & Chr(10) & "---------------------------------------------" & Chr(13) & Chr(10) & StrMsg & Chr(13) & Chr(10) & "---------------------------------------------" & Chr(13) & Chr(10) & Chr(13) & Chr(10) & "If left as is, it will not print out corectly." & vbCrLf & "Would you like these links to be removed automaticaly?", vbYesNo + vbExclamation, "Warning")
                End If

                If Ret = MsgBoxResult.Yes Then

                    If Not CommonDataFunctions.ExecuteSQL("DELETE FROM FROM D_LetterLink WHERE D_LetterLink.LetterLink_ID in " & StrID) Then
                        Exit Sub
                    End If

                    MsgBox("Links to these Letterpacks have been removed. Please now check those letterpacks to ensure they have the correct letters for all client types." & vbCrLf & vbCrLf & StrMsg, MsgBoxStyle.Information, "Links deleted")
                Else
                    MsgBox("Links have been left as they are, please either remove the links by hand or else amend the letter so it does not use inappropriate bookmarks. If it is left as is, this letter will not print correctly for all customer types.", MsgBoxStyle.Information)
                End If
            Else
                myData.Dispose()
            End If

        End If


        'List the unrecognised bookmarks

        If Not (StrUnknown = "") Then
            MsgBox("The following bookmarks were not recognised" & Chr(13) & Chr(10) & "------------------------------------------------------" & Chr(13) & Chr(10) & StrUnknown, MsgBoxStyle.Information)
        End If

        'is this letter ok for the selected letter type

        If StrInvalid = "" Then
            Ret = MsgBox("This letter is ok for use with the selected lettertype", MsgBoxStyle.Information)
        Else
            Ret = MsgBox("This letter is not appropriate for use with the " & Me.drpType.Text & " lettertype. " & Chr(13) & Chr(10) & "The following bookmarks were found that will not work" & Chr(13) & Chr(10) & "-------------------------------------------------------" & Chr(13) & Chr(10) & StrInvalid & Chr(13) & Chr(10) & "-------------------------------------------------------" & Chr(13) & Chr(10) & Chr(13) & Chr(10) & "You need to either remove them from the letter or else select a different lettertype", MsgBoxStyle.Exclamation, "Error")
        End If

        Me.grpClientTypes.IsEnabled = True


    End Sub

    Private Sub txtPath_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPath.TextChanged
        If Me.txtPath.Text.Trim.Length > 0 Then
            Me.drpType.IsEnabled = True
        Else
            Me.drpType.IsEnabled = False
        End If
    End Sub

    Private Sub drpType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles drpType.SelectionChanged

        If Me.drpType.SelectedIndex >= 0 Then
            Me.btnScanBookmarks.IsEnabled = True
        Else
            Me.btnScanBookmarks.IsEnabled = False
        End If

    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        'Validation

        Dim Msg As New StringBuilder
        Dim OutputName As String
        Dim myLetter As Letters.LetterInfo

        If Me.txtName.Text.Trim = "" Then
            MsgBox("Please enter a valid name", MsgBoxStyle.Exclamation, "Error")
            Exit Sub
        End If

        If Me.txtName.Text.Trim.Length > 100 Then
            MsgBox("Letter name is too long, cannot be more than 100 characters.", MsgBoxStyle.Exclamation, "Error")
            Exit Sub
        End If

        If Me.txtPath.Text.Trim = "" Then
            MsgBox("No filepath, unable to save.", MsgBoxStyle.Exclamation, "Error")
            Exit Sub
        End If

        If Me.txtPath.Text.Trim.Length > 150 Then
            MsgBox("Filepath is too long, please shorten. Cannot be more than 150 characters.", MsgBoxStyle.Exclamation, "Error")
            Exit Sub
        End If

        If Me.drpType.SelectedIndex = -1 Then
            MsgBox("Please select a letter type", MsgBoxStyle.Exclamation, "Error")
            Exit Sub
        End If

        'IntFileType = Me.Frm_DocType

        If Letters.LetterAlreadyRegistered(Me.LetterId, Me.txtPath.Text) Then
            'Already registered
            Exit Sub
        End If


        'Check if letter name has already been used.
        If Letters.LetterNameInUse(Me.LetterId, Me.txtName.Text) Then
            'In use
            Exit Sub
        End If

        'Build Query
        If Me.LetterId > 0 Then
            'Updating existing letter

            With Msg
                .Append("Letter number " & Me.LetterId & " (" & Me.LetterName & ")")
                .Append(" saved with the following details:" & vbCrLf & vbCrLf)
                .Append("Name       : " & Me.txtName.Text.Trim)
                .Append("Filepath   : " & Me.txtPath.Text.Trim)
                .Append("Type       : " & Me.drpType.Text)
                .Append("Client Type: ")

                Select Case Me.ClientType
                    Case 0
                        .Append("All")

                    Case 1
                        .Append("Private")

                    Case 2
                        .Append("Corporate")
                End Select

                .Append("Output Type: " & Me.OutputType)
            End With

            OutputName = Letters.OutputName(Me.OutputType)

            myLetter = New Letters.LetterInfo

            With myLetter
                .LetterId = Me.LetterId
                .LetterName = Me.txtName.Text.Trim
                .Filepath = Me.txtPath.Text.Trim
                .CustomerType = Me.ClientType
                .OutputType = Me.OutputType
                .LetterType = Me.drpType.SelectedValue
            End With

            Letters.SaveLetter(myLetter, GlobalCRM.CurrentConName)


        Else
            'Creating new letter


            OutputName = Letters.OutputName(Me.OutputType)

            With Msg
                .Append("Name       : " & Me.txtName.Text)
                .Append("Filepath   : " & Me.txtPath.Text)
                .Append("Type       : " & Me.drpType.Text)
                .Append("Client Type: ")

                Select Case Me.ClientType
                    Case 0
                        .Append("All")

                    Case 1
                        .Append("Private")

                    Case 2
                        .Append("Corporate")
                End Select

                .Append("Output Type: " & Me.OutputType)
                .Append(OutputName)
            End With

        End If

        With Msg
            .Append(vbCrLf & "File Type: ")

            If Me.DocumentType = 2 Then
                .Append("PDF")
            Else
                .Append("Word Template")
            End If
        End With

        myLetter = New Letters.LetterInfo

        With myLetter
            .LetterId = 0
            .LetterName = Me.txtName.Text.Trim
            .Filepath = Me.txtPath.Text.Trim
            .CustomerType = Me.ClientType
            .OutputType = Me.OutputType
            .LetterType = Me.drpType.SelectedValue
        End With

        Me.LetterId = Letters.SaveLetter(myLetter, GlobalCRM.CurrentConName)



        Msg.Insert(0, "New Letter registered with the following details:" & vbCrLf & vbCrLf & "Letter ID  : " & Me.LetterId & vbCrLf)
        Dim tskEvents As New TasksEvents
        tskEvents.GblFunc_Add_SysEvent("Admin (SL)", Msg.ToString)

        'DoCmd.Close(acForm, "FMA_LetterDetails")


        If Me.DocumentType = 2 Then
            'PDF scan for fields, register on the system then prompt to setup associations.

            Dim FieldCount As Integer

            FieldCount = Letters.ScanPDF(Me.LetterId)

            If FieldCount = 0 Then
                MsgBox("This PDF contains no fillable fields, therefore it can only be printed as is. If you want database fields added, fillable fields need to be added to the PDF. Speak to IT for more info on this.", MsgBoxStyle.Exclamation, "PDF Scan")
            Else
                If MsgBox("This PDF contains " & FieldCount & " fillable fields. Do you wish to associate them with bookmarks?", vbYesNo + vbQuestion, "PDF Scan") Then
                    'Open association form
                    'DoCmd.OpenForm("FMA_SL_PDFAssociations")

                    'Form_FMA_SL_PDFAssociations.Txt_ID = LID

                    'Call Form_FMA_SL_PDFAssociations.SQL_FieldList()
                    'Call Form_FMA_SL_PDFAssociations.SQL_BookmarkList()

                End If
            End If
        End If



    End Sub
End Class
